package com.itheima.health.service.impl;

import com.itheima.health.dto.OrderDTO;
import com.itheima.health.mapper.MemberMapper;
import com.itheima.health.pojo.Member;
import com.itheima.health.service.MemberService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * 会员SERVICE实现类
 */
@Service
@Slf4j
@Transactional
public class MemberServiceImpl implements MemberService {
    @Autowired
    private MemberMapper memberMapper;

    @Override
    public Member register(OrderDTO dto) throws ParseException {
        Member memberDB = memberMapper.selectByIdCard(dto.getIdCard());
        if (memberDB != null){
            return memberDB;
        }

        //获取参数
        String idCard = dto.getIdCard();
        String name = dto.getName();
        String sex = dto.getSex();
        String telephone = dto.getTelephone();
        //150404199908190336
        String birthDayStr = idCard.substring(6, 14);

        //处理生日
        Date birthDay = new SimpleDateFormat("yyyyMMdd").parse(birthDayStr);
        //注册时间
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        //封装参数
        Member member = Member.builder()
                .idCard(idCard)
                .regTime(sdf.parse(dto.getOrderDate()))
                .phoneNumber(telephone)
                .name(name)
                .sex(sex)
                .birthday(birthDay).build();
        memberMapper.insert(member);
        return member;
    }

    /**
     * 计算年龄
     * @param idCard
     * @return
     * @throws ParseException
     */
    @Override
    public Integer calculateAge(String idCard) throws ParseException {
        //截取子串
        String birthDayStr = idCard.substring(6, 14);
        Date birthDay = new SimpleDateFormat("yyyyMMdd").parse(birthDayStr);

        return calculate(birthDay, new Date());
    }

    private Integer calculate(Date birthDate, Date currentDate) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(birthDate);
        int birthYear = calendar.get(Calendar.YEAR);
        int birthMonth = calendar.get(Calendar.MONTH);
        int birthDay = calendar.get(Calendar.DAY_OF_MONTH);

        calendar.setTime(currentDate);
        int currentYear = calendar.get(Calendar.YEAR);
        int currentMonth = calendar.get(Calendar.MONTH);
        int currentDay = calendar.get(Calendar.DAY_OF_MONTH);

        // 计算年龄
        int age = currentYear - birthYear;
        if (currentMonth < birthMonth ||
                (currentMonth == birthMonth && currentDay < birthDay)) {
            age--;
        }

        return age;
    }
}
